package controller

import (
	"gostore/dao"
	"gostore/model"
	"gostore/router"
	"strconv"

	com "gostore/common"

	"github.com/gin-gonic/gin"
)

type SystemUserTaskControllerT struct {
	BaseControllerT
}

var SystemUserTaskController = SystemUserTaskControllerT{}

func (o SystemUserTaskControllerT) List(c *gin.Context) {
	id := c.Param("id")
	levelId, err := strconv.Atoi(id)
	if err != nil {
		com.Err(c, 503, "错误的参数id")
		return
	}

	list, err := dao.SystemUserTaskDao.ListByLevelId(levelId)
	if err != nil {
		com.Err(c, 503, "查询失败")
		return
	}

	mdata := make(map[string]interface{}, 0)
	mdata["list"] = list

	com.Ok(c, mdata)
	return
}

func (o SystemUserTaskControllerT) Create(c *gin.Context) {
	id := c.Param("id")
	levelId, err := strconv.Atoi(id)
	if err != nil {
		com.Err(c, 503, "错误的参数id")
		return
	}
	sUserTask := new(model.SystemUserTask)
	err = c.ShouldBind(&sUserTask)

	if err != nil {
		com.Err(c, 503, "传上来的内容有错误")
		return
	}
	sUserTask.LevelId = levelId
	err = dao.SystemUserTaskDao.Save(sUserTask)
	if err != nil {
		com.Err(c, 503, "创建失败")
		return
	}
	com.Ok(c, sUserTask)
	return
}

func (o SystemUserTaskControllerT) Update(c *gin.Context) {
	id := c.Param("id")
	levelId, err := strconv.Atoi(id)
	if err != nil {
		com.Err(c, 503, "错误的参数id")
		return
	}

	taskIdStr := c.Param(":taskId")
	taskId, err := strconv.Atoi(taskIdStr)
	if err != nil {
		com.Err(c, 503, "错误的参数id")
		return
	}

	sUserTask := new(model.SystemUserTask)
	err = c.ShouldBind(&sUserTask)

	if err != nil {
		com.Err(c, 503, "传上来的内容有错误")
		return
	}
	sUserTask.LevelId = levelId
	sUserTask.Id = taskId
	err = dao.SystemUserTaskDao.Save(sUserTask)
	if err != nil {
		com.Err(c, 503, "更新失败")
		return
	}
	com.Ok(c, sUserTask)
	return
}

func (o SystemUserTaskControllerT) AddNewRoutes() {
	router.AddRouteGroup("api/systemUserLevel", []router.Route{
		router.Route{
			Method:  router.MGet,
			Path:    "/:id/task",
			Handler: o.List,
		},
	})
	router.AddRouteGroup("api/systemUserLevel", []router.Route{
		router.Route{
			Method:  router.MPost,
			Path:    "/:id/task",
			Handler: o.Create,
		},
	})
	router.AddRouteGroup("api/systemUserLevel", []router.Route{
		router.Route{
			Method:  router.MPut,
			Path:    "/:id/task/:taskId",
			Handler: o.Update,
		},
	})
}
